<?php

namespace App\Models\Factory;


use App\Helpers\Http\HttpClient;
use App\Helpers\Utils;
use App\Models\AbsModelFactory;
use App\Models\Orm\Collection;
use App\Models\Orm\DataProductApply;
use App\Models\Orm\DataProductCount;
use App\Models\Orm\DataProductDetailLog;
use App\Models\Orm\Labels;
use App\Models\Orm\Loading;
use App\Models\Orm\PlatFormDetail;
use App\Models\Orm\Product;
use App\Models\Orm\ProductLabels;
use App\Models\Orm\Recommand;
use App\Models\Orm\Vip;
use JPush\Config;
use DB;


/**
 * 关于产品的工厂
 * Class ProductFactory
 * @package App\Models\Factory
 */
class ProductFactory extends AbsModelFactory
{



    /**
     * 通过手机号查询用户信息
     */
    public static function getList($type)
    {
        if($type == 1)
        {
            $data = Product::select('id','name','link','product_logo','product_introduction','interest_algorithm','min_algorithm','max_algorithm','maximum_amount','minimum_amount')->where('state',1)->orderBy('index','desc')->get()->toArray();

        }elseif($type == 2){

            $data = Product::where('status',1)->where('hot',1)->get()->toArray();

        }elseif($type == 3)
        {  $data = Product::where('status',1)->where('online',1)->get()->toArray();

        }elseif($type == 4){
            $data = Product::where('status',1)->orderBy('min_algorithm','asc')->get()->toArray();

        }elseif($type == 5)
        {
            $data = Product::where('status',1)->orderBy('fastest','asc')->get()->toArray();

        }elseif($type == 6){
            $data = Product::select('id','name','link','product_logo','product_introduction','interest_algorithm','min_algorithm','max_algorithm','maximum_amount','minimum_amount')->where('status',1)->orderBy('index','desc')->get()->toArray();

        }elseif($type == 7){


//            $ids = Loading::select('product_id')->orderBy('sort','aesc')->get()->toArray();
//            $data = Product::select();
           $data = DB::table('product')
               ->select('product.id','loading.sort','name','link','product_logo','product_introduction','interest_algorithm','min_algorithm','max_algorithm','maximum_amount','minimum_amount')
               ->Join('loading','product.id','=','loading.product_id')
                ->orderBy('loading.sort','asc')
                ->get()
                ->toArray();

               foreach ($data as $k =>$v)
            {

                $data[$k] -> interest_algorithm = Product::getInterestAlgorithmText($v ->interest_algorithm);
                $data[$k] -> min_algorithm  = $v ->min_algorithm .'%';
                $data[$k] -> max_algorithm  = $v -> max_algorithm .'%';

            }

            return $data;


        }
        elseif($type == 8){

            $data = DB::table('product')
                ->select('product.id','sms.sort','name','link','product_logo','product_introduction','interest_algorithm','min_algorithm','max_algorithm','maximum_amount','minimum_amount','hot','online')
                ->Join('sms','product.id','=','sms.product_id')
                ->orderBy('sms.sort','asc')
                ->get()
                ->toArray();

            foreach ($data as $k =>$v)
            {

                $data[$k] -> interest_algorithm = Product::getInterestAlgorithmText($v ->interest_algorithm);
                $data[$k] -> min_algorithm  = $v ->min_algorithm .'%';
                $data[$k] -> max_algorithm  = $v -> max_algorithm .'%';

            }

            return $data;
        }elseif($type == 9) {

            $data = DB::table('product')
                ->select('product.id','project.sort','name','link','product_logo','product_introduction','interest_algorithm','min_algorithm','max_algorithm','maximum_amount','minimum_amount')
                ->Join('project','product.id','=','project.product_id')
                ->orderBy('project.sort','asc')
                ->get()
                ->toArray();

            foreach ($data as $k =>$v)
            {

                $data[$k] -> interest_algorithm = Product::getInterestAlgorithmText($v ->interest_algorithm);
                $data[$k] -> min_algorithm  = $v ->min_algorithm .'%';
                $data[$k] -> max_algorithm  = $v -> max_algorithm .'%';

            }

            return $data;
        }elseif($type == 10) {
            $data = Product::select('id','name','link','product_logo','product_introduction','interest_algorithm','min_algorithm','max_algorithm','maximum_amount','minimum_amount')->where('status',1)->where('state',1)->orderBy('index','desc')->get()->toArray();

        }elseif($type == 11) {

            $data = DB::table('product')
                ->select('product.id','sms_new.sort','name','link','product_logo','product_introduction','interest_algorithm','min_algorithm','max_algorithm','maximum_amount','minimum_amount')
                ->Join('sms_new','product.id','=','sms_new.product_id')
                ->orderBy('sms_new.sort','asc')
                ->get()
                ->toArray();

            foreach ($data as $k =>$v)
            {

                $data[$k] -> interest_algorithm = Product::getInterestAlgorithmText($v ->interest_algorithm);
                $data[$k] -> min_algorithm  = $v ->min_algorithm .'%';
                $data[$k] -> max_algorithm  = $v -> max_algorithm .'%';

            }

            return $data;

        } else {
            $data = Product::where('status',1)->orderBy('passing_rate','desc')->get()->toArray();

        }

        foreach ($data as $k =>$v)
        {

            $data[$k]['interest_algorithm'] = Product::getInterestAlgorithmText($v['interest_algorithm']);
            $data[$k]['min_algorithm'] = $v['min_algorithm'].'%';
            $data[$k]['max_algorithm'] = $v['max_algorithm'].'%';
            $data[$k]['repayment_total'] = $v['minimum_amount'] + round($v['min_algorithm']*$v['minimum_amount']*0.01,2);
            $apply_total = DB::table('data_product_count')->where("product_id",$v['id'])->sum("apply_total");
            $data[$k]['apply'] = $apply_total * 1000;

        }
        return $data;
    }



    //插入产品流水表
    public static  function addProductApply($user,$info)
    {

        $data['user_id'] = $user->id;
        $data['userphone'] = $user->userphone;
        $data['product_id'] = $info['product_id'];
//        $data['app_name'] = $info['app_name'];
        $info['app_name'] = isset($info['app_name']) ? $info['app_name'] : '非安卓';
        $app_names = config('xianjindai.app_name');
        $data['app_name'] = array_search($info['app_name'], $app_names);
        $data['app_name'] = $data['app_name'] ? $data['app_name'] : 0;
        $data['channel'] = $info['channel'];
        //插入渠道流水表
//        $channel_nid = $user->channel ? : 'weixin1'; //如果用户信息里没有渠道信息，默认为weixn1

        if($data['channel'] == 'xinshi' || $data['channel'] == 'fengxiang' || $data['channel'] == 'xianjindai' || $data['channel'] == 'yidong' || $data['channel'] == 'liantong' ){
            $origin = 1;
            if($data['channel'] == 'xianjindai'){

                $data['channel']=2;
            }

            if($data['channel'] == 'yidong'){

                $data['channel']=58;
            }


            if($data['channel'] == 'liantong'){

                $data['channel']=57;
            }

            if($data['channel'] == 'fengxiang'){

                $data['channel']=63;
            }

            if($data['channel'] == 'xinshi'){

                $data['channel']=64;
            }


        }else{

            $channels = DeliveryFactory::getDeliveryByNid($data['channel']);
//            $url     = "http://www.shoujijiekuan.com//Web/CheckTel.aspx?CellNo=".$user->userphone;
//            $promise = HttpClient::i()->request('GET', $url);
//            $result  = $promise->getBody()->getContents();
//            if($result == 0)
//            {
//                $origin = 1;
//            }else{
//                $origin = 2;
//            }
            $origin = 1;
            $data['channel'] =  $channels ? $channels->id : 1;
        }

        $data['user_origin']   = $origin;
        //获取产品名
        $product = ProductFactory::getProduct($info['product_id']);
        $product_name  = $product ? $product->name : '产品';
        $data['product_name'] = $product_name;
        $data['create_ip'] = Utils::ipAddress();
        $data['create_at'] = date('Y-m-d H:i:s',time());
//        dd($data);
        $result = DataProductApply::create($data);
        return $result ? true :false;
    }

    //插入产品流水表
    public static  function addProductDetail($user,$info)
    {

        $data['user_id'] = $user->id;
        $data['userphone'] = $user->userphone;
        $data['product_id'] = $info['product_id'];
        $channel_nid = $user->channel_nid ? : 'weixin1'; //如果用户信息里没有渠道信息，默认为weixn1
        $channels = DeliveryFactory::getDeliveryByNid($channel_nid);
        $data['channel'] =  $channels ? $channels->id : 1;

        $info['app_name'] = isset($info['app_name']) ? $info['app_name'] : '非安卓';
        $app_names = config('xianjindai.app_name');
        $data['app_name'] = array_search($info['app_name'], $app_names);
        $data['app_name'] = $data['app_name'] ? $data['app_name'] : 0;
        //获取产品名
        $product = ProductFactory::getProduct($info['product_id']);
        $product_name  = $product ? $product->name : '产品';
        $data['product_name'] = $product_name;
        $data['create_ip'] = Utils::ipAddress();
        $data['create_at'] = date('Y-m-d H:i:s',time());
        $result = DataProductDetailLog::create($data);

        return $result ? true :false;
    }


    //获取产品信息
    public static  function getProduct($product_id)
    {
        $product = Product::where('id',$product_id)->first();

        return $product ? $product : '';
    }

    /**
     * 展示所有标签
     */
    public static function Showlabels()
    {
        $opinion = Labels::get();
        return $opinion;
    }

//    /**
//     * 递归函数
//     */
//    public static function digui($new)
//    {
//
//            // 获取去掉重复数据的数组
//            $unique_arr = array_unique($new);
//            // 获取重复数据的数组
//           $repeat_arr = array_diff_assoc($new, $unique_arr);
//            return $repeat_arr == [] ? $unique_arr :self::digui($repeat_arr);
//
//    }

    /**
     * 筛选接口
     */
    public static function Screening($amount)
    {

        $data = Product::where('status',1)->where('maximum_amount', '>=', $amount)->get()->toArray();



        foreach ($data as $k =>$v)
        {

            $data[$k]['interest_algorithm'] = Product::getInterestAlgorithmText($v['interest_algorithm']);
            $data[$k]['min_algorithm'] = $v['min_algorithm'].'%';
            $data[$k]['max_algorithm'] = $v['max_algorithm'].'%';
            $data[$k]['fastest'] = $v['fastest'].' '.Product::getFastestTypeText($v['fastest_type']);
            $data[$k]['prepayment'] = Product::getPrepaymentText($v['prepayment']);
            switch ( $data[$k]['review']) {
                case 0:
                    $data[$k]['review'] = '自动审核';
                    break;
                case 1:
                    $data[$k]['review'] = '人工审核';
                    break;
                case 2:
                    $data[$k]['review'] = '线下审核';
                    break;
            }
        }
        return $data;
    }

    /**
     * 根据产品名字查询产品
     */
    public static function getProductByName($data)
    {
        $product = Product::select('id')->where(['pname' => $data])->first();
        return $product;

//        if(empty($product))
//        {
//            return true;
//        }else{
//            return false;
//        }
    }


    /* 获取产品详情表
    */

    public static function productDetail($id, $token = "")
    {


        $product = Product::with('labels')->where('id', $id)->get();
        $product = $product->toArray();
        $product = $product[0];

        $pl_id = $product['pl_id'];

        if (!empty($token)) {
            $user = UserFactory::getUserByToken($token);
            if($user) {
                $result = Collection::where(['uid' => $user->id, 'product_id' => $id])->first();
                if ($result) {
                    $product['collectioStatus'] = 1;

                } else {
                    $product['collectioStatus'] = 2;
                }
            }
            $product['collectioStatus'] = 3;

        }
        $platform = PlatFormDetail::select('pl_name', 'introduction', 'registered_time')->where('pl_id', $pl_id)->get();
        $platform = $platform->toArray();
        $platform = $platform[0];
        $product['platformdetail'] = $platform;
//        var_dump($product);
//        die;interest_algorithm
        switch ($product['interest_algorithm']) {
            case 0:
                $product['interest_algorithm'] = '日利率';
                break;
            case 1:
                $product['interest_algorithm'] = '月利率';
                break;
        }
        switch ($product['review']) {
            case 0:
                $product['review'] = '自动审核';
                break;
            case 1:
                $product['review'] = '人工审核';
                break;
            case 2:
                $product['review'] = '线下审核';
                break;
        }


        switch ($product['repayment']) {
            case 0:
                $product['repayment'] = '等额本息';
                break;
            case 1:
                $product['repayment'] = '等额本金';
                break;
            case 2:
                $product['repayment'] = '一次性还款';
                break;
            case 3:
                $product['repayment'] = $product['repayments'];
                break;
        }

        switch ($product['repayment_channels']) {
            case 0:
                $product['repayment_channels'] = 'ATM还款';
                break;
            case 1:
                $product['repayment_channels'] = '手机银行还款';
                break;
            case 2:
                $product['repayment_channels'] = 'APP还款';
                break;
            case 3:
                $product['repayment_channels'] = '其他';
                break;
        }

        switch ($product['prepayment']) {
            case 0:
                $product['prepayment'] = '可以';
                break;
            case 1:
                $product['prepayment'] = '不可以';
                break;
            case 2:
                $product['prepayment'] = $product['prepayments'];
                break;

        }

        switch ($product['actual_account']) {
            case 0:
                $product['actual_account'] = '全部到账';
                break;
            case 1:
                $product['actual_account'] = '扣除手续费';
                break;
            case 2:
                $product['actual_account'] = '扣除手续费和利息';
                break;
            case 3:
                $product['actual_account'] = $product['actual_accounts'];
                break;

        }

        $product['crowds'] = explode(',', $product['crowd']);
        $uu = '';
        foreach ($product['crowds'] as $u) {
            switch ($u) {
                case 1:
                    $uu = '上班族';
                    break;
                case 2:
                    $uu .= ' 学生党';
                    break;
                case 3:
                    $uu .= ' 逍遥客';
                    break;
                case 4:
                    $uu .= ' 企业主';
                    break;
            }
        }
        $product['crowd'] = $uu;


        $product['use'] = explode(',', $product['use']);
        $uu1 = '';
        foreach ($product['use'] as $u) {
            switch ($u) {
                case 0:
                    $uu1 = '秒贷现金';
                    break;
                case 1:
                    $uu1 .= '、还信用卡';
                    break;
                case 2:
                    $uu1 .= '、消费分期';
                    break;
            }
        }
        $product['use'] = $uu1;
        return $product;
    }

    /**
     * 根据产品名字查询产品
     */
    public static function getUrl($name)
    {
        $product = Product::where('name',$name)->where('state',1)->first();

        return $product ? $product -> link : '';

    }

    /**
     *
     * 通过手机号查询用户信息
     */
    public static function getRecommand()
    {
        $ids = Recommand::select('product_id')->get()->toArray();
        $data = Product::whereIn('id',$ids)->get();
        foreach ($data as $k =>$v)
        {

            $data[$k]['interest_algorithm'] = Product::getInterestAlgorithmText($v['interest_algorithm']);
            $data[$k]['min_algorithm'] = $v['min_algorithm'].'%';
            $data[$k]['max_algorithm'] = $v['max_algorithm'].'%';
            $data[$k]['fastest'] = $v['fastest'].' '.Product::getFastestTypeText($v['fastest_type']);
            $data[$k]['prepayment'] = Product::getPrepaymentText($v['prepayment']);
            $data[$k]['repayment_total'] = $v['minimum_amount'] + round($v['min_algorithm']*$v['minimum_amount']*0.01,2);
            $apply_total = DB::table('data_product_count')->where("product_id",$v['id'])->sum("apply_total");
            $data[$k]['apply'] = $apply_total * 1000;

        }
        return $data;
    }

    /**
     *
     * 通过手机号查询用户信息
     */
    public static function getVip()
    {
        $ids = Vip::select('product_id')->get()->toArray();
        $data = Product::whereIn('id',$ids)->get();
        foreach ($data as $k =>$v)
        {

            $data[$k]['interest_algorithm'] = Product::getInterestAlgorithmText($v['interest_algorithm']);
            $data[$k]['min_algorithm'] = $v['min_algorithm'].'%';
            $data[$k]['max_algorithm'] = $v['max_algorithm'].'%';
            $data[$k]['fastest'] = $v['fastest'].' '.Product::getFastestTypeText($v['fastest_type']);
            $data[$k]['prepayment'] = Product::getPrepaymentText($v['prepayment']);
            $data[$k]['repayment_total'] = $v['minimum_amount'] + round($v['min_algorithm']*$v['minimum_amount']*0.01,2);
            $apply_total = DB::table('data_product_count')->where("product_id",$v['id'])->sum("apply_total");
            $data[$k]['apply'] = $apply_total * 1000;

        }

        $todayStart= date('Y-m-d 00:00:00', time()); //2016-11-01 00:00:00

        $todayEnd= date('Y-m-d 23:59:59', time()); //2016-11-01 23:59:59
        $todayApply =  DataProductApply::select([DB::raw('count(user_id) as total'),])->where("create_at",'>',$todayStart)->where("create_at",'<',$todayEnd)->get();
        $data['number'] = $todayApply ? $todayApply[0]['total'] : 0;

        return $data;
    }






}